package com.powernode.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import reactor.core.publisher.Mono;

import java.time.Duration;

@Configuration
public class GatewayConfig {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Bean
    public RouteLocator routeLocator(RouteLocatorBuilder builder) {
        return builder.routes()
                .route("auth-server-id", r -> r.path("/oauth/token")
                        .filters(f -> f.modifyResponseBody(String.class, String.class, (exchange, result) -> {
                            JSONObject jsonObject = JSON.parseObject(result);
                            String token = jsonObject.getString("access_token");
                            Long expires_in = jsonObject.getLong("expires_in");
                            if (StringUtils.hasText(token))
                                stringRedisTemplate.opsForValue().set("bearer " + token, "", Duration.ofSeconds(expires_in));
                            return Mono.just(result);
                        }))
                        .uri("lb://auth-server")).build();
    }
}
